<?php
/**
 *                          _ooOoo_
 *                         o8888888o
 *                         88" . "88
 *                         (| -_- |)
 *                         O\  =  /O
 *                      ____/`---'\____
 *                    .'  \|     |//  `.
 *                   /  \|||  :  |||//  \
 *                  /  _||||| -:- |||||-  \
 *                  |   | \\  -  /// |   |
 *                  | \_|  ''\---/''  |   |
 *                  \  .-\__  `-`  ___/-. /
 *                ___`. .'  /--.--\  `. . __
 *             ."" '<  `.___\_<|>_/___.'  >'"".
 *            | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *            \  \ `-.   \_ __\ /__ _/   .-` /  /
 *       ======`-.____`-.___\_____/___.-`____.-'======
 *                          `=---='
 *
 *==================================================
 *                  佛祖保佑        永无BUG
 *         佛曰:
 *                写字楼里写字间，写字间里程序员；
 *                程序人员写程序，又拿程序换酒钱。
 *                酒醒只在网上坐，酒醉还来网下眠；
 *                酒醉酒醒日复日，网上网下年复年。
 *                但愿老死电脑间，不愿鞠躬老板前；
 *                奔驰宝马贵者趣，公交自行程序员。
 *                别人笑我忒疯癫，我笑自己命太贱；
 *                不见满街漂亮妹，哪个归得程序员？
 *==================================================
 */

 
/**
 * 大营配置
 * @author  Don
 * @date    2019-05-22
 */

namespace App\Admin\Controllers\kly;

use App\Models\kly\Kly_camp;
use App\Models\kly\Kly_student;
use App\Models\Squad;
use App\Models\Student;
use DB;
use Encore\Admin\Widgets\Table;
use Illuminate\Http\Request;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
// use Encore\Admin\Grid\Displayers\Modal;


class Camp_group_configController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use($request){

            $content->header('小组');
            $content->description('配置');
            
            $content->body($this->grid($request)->render());
            $content->body($this->add_stu_to_camp_group_form());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('小组');
            $content->description(trans('admin.edit'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('小组');
            $content->description(trans('admin.create'));

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid(Request $request)
    {
        return Admin::grid(Kly_camp::class, function (Grid $grid) use($request){
            if (!is_null($request['pid'])) {
                $grid->model()->where('pid',$request['pid']);
            }else
            {
                $grid->model()->where('camp_type','3');
            }
            
            if (!Admin::user()->isAdministrator()) {
                //$grid->model()->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)');
				$grid->model()->where('camp_type','3')->where(function($query){$query->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)')->orWhereRaw('find_in_set('.Admin::user()->id.',`tutors`)');});
            }
            $grid->model()->orderBy('id', 'desc');
            $grid->name(trans('admin.name'));
            $grid->column('所属小营')->display(function(){
                return Kly_camp::where('id',$this->pid)->value('name');
            });
            $grid->chargeman('组长')->display(function($chargeman){
                return DB::table('students')->where('id',$this->chargeman)->value('en_name');
            })->label('info');
            $grid->column('人数')->display(function(){
                $students = Kly_student::where('camp_group_id',$this->id)->count();
                return '<a style="cursor:pointer;" href="kly_student_list?g_id='.$this->id.'">'.$students."</a>";
            });
            $grid->actions(function ($actions) {
                $actions->disableView();
                $actions->disableDelete();
				$actions->disableEdit();
                $camp_info = $actions->row; 
                $big_camp_id = Kly_camp::where('id',$camp_info->pid)->value('pid');
                $selected_students = implode(',',Kly_student::where(['big_camp_id'=>$big_camp_id,'small_camp_id'=>$camp_info->pid,'camp_group_id'=>$camp_info->id])->pluck('student_id')->toArray());
                $actions->prepend('<a data-toggle="modal" data-target="#myModal" data-group_id="'.$actions->getKey().'" data-students="'.$selected_students.'"><i class="fa fa-user-plus"></i></a>');
            });
			
            //禁用导出按钮
            $grid->disableExport();
            //禁用筛选按钮
            $grid->disableFilter();

            $grid->tools(function ($tools) { 
                //关闭批量删除 
                $tools->batch(function ($batch) { 
                    $batch->disableDelete(); 
                });
            });
        });
    }

    protected function add_stu_to_camp_group_form()
    {
        return view('admin.kly.add_stu_to_camp_group_form');
    }

    protected function get_camp_group_stus(Request $request)
    {
        $group_id = $request['group_id'];
		//找出对应小组的组长ID
		$camp_chargeman = Kly_camp::where('id',$group_id)->value('chargeman');
		//找出对应小组所属的小营ID
		$pid = Kly_camp::where('id',$group_id)->value('pid');
		//找出所属小营还未分配的学员ID列表
		$to_assign_studentIds = Kly_student::where('small_camp_id',$pid)->where('camp_group_id','0')->pluck('student_id')->toArray();
        $current_camp_done_assign_stuIds = Kly_student::where('camp_group_id',$group_id)->where('student_id','!=',$camp_chargeman)->pluck('student_id')->toArray();
		if(count($current_camp_done_assign_stuIds)>0)
		{
			$can_assign_stuIds = array_merge($current_camp_done_assign_stuIds,$to_assign_studentIds);
		}else{
			$can_assign_stuIds = $to_assign_studentIds;
		}
        $students = DB::table('students as stu')->join('squads as s',function($join){
            $join->on('stu.squad_id','=','s.id');
        })->whereIn('stu.id',$can_assign_stuIds)->where('stu.status','=','1')->orderBy('s.name')->select('stu.id as studentId',DB::raw("concat(stu.ch_name,' - ',stu.en_name,'(',s.name,')') as studentName"))->get();
        $arr=array();
        foreach($students as $k => $v){
            $arr[] = array('id'=>$v->studentId,'text'=>$v->studentName);
        }
        return $arr;
    }

    protected function save_camp_group_students(Request $request)
    {
        $group_students = $request['students'];
        $camp_group_id = $request['group_id'];
        $small_camp_id = Kly_camp::where('id',$camp_group_id)->value('pid');
        $big_camp_id = Kly_camp::where('id',$small_camp_id)->value('pid');
		$camp_group_students = Kly_student::where(['big_camp_id'=>$big_camp_id,'small_camp_id'=>$small_camp_id,'camp_group_id'=>$camp_group_id,'is_chargeman'=>'0'])->pluck('student_id')->toArray();
		$diff_students1 = array_diff($group_students,$camp_group_students);
		$diff_students2 = array_diff($camp_group_students,$group_students);
		
		var_dump($diff_students1);
		var_dump($diff_students2);
		if(count($camp_group_students)>0){
			if(!is_null($diff_students1))
			{
				//加了学员
				foreach ($diff_students1 as $value) {
					Kly_student::where('student_id',$value)->update(['camp_group_id'=>$camp_group_id]);
				}
			}
			if(!is_null($diff_students2)){
				foreach ($diff_students2 as $value) {
					Kly_student::where('student_id',$value)->update(['camp_group_id'=>0]);
				}
			}
		}else{
			foreach ($diff_students1 as $value) {
				Kly_student::where('student_id',$value)->update(['camp_group_id'=>$camp_group_id]);
			}
		}
        
        
    }
    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Kly_camp::class, function (Form $form) {
            $form->display('id', 'ID');
            $form->text('name','名称')->rules('required')->rules('required')->addElementLabelClass('must-input');
            $form->hidden('camp_type')->value('3');
			if(Admin::user()->isAdministrator()){
				$pid_options = Kly_camp::where('camp_type','2')->pluck('name','id');
			}else{
				$pid_options = Kly_camp::where('camp_type','2')->where(function($query){$query->WhereRaw('find_in_set('.Admin::user()->id.',`leaders`)')->ORWhereRaw('find_in_set('.Admin::user()->id.',`tutors`)');})->pluck('name','id');
			}
            $form->select('pid','所属小营')->options($pid_options)->load('chargeman','/api/get_chargeman_by_small_camp')->rules('required')->addElementLabelClass('must-input');
            //$all_admin_users = DB::table('admin_users')->pluck('username','id');
            $form->select('chargeman', '组长')->rules('required')->addElementLabelClass('must-input');
            
            $form->saved(function (Form $form) {
                $camp = Kly_camp::find($form->model()->id);
                $camp_squads = Kly_camp::where('id',$form->pid)->value('squads');
				$camp_leaders = Kly_camp::where('id',$form->pid)->value('leaders');
				$camp_tutors = Kly_camp::where('id',$form->pid)->value('tutors');
                $camp_term = Kly_camp::where('id',$form->pid)->value('term_id');
                $camp->squads = $camp_squads;
				$camp->leaders = $camp_leaders;
				$camp->tutors = $camp_tutors;
                $camp->term_id = $camp_term;
                $camp->save();
				
				//分配小组长后,在Kly_students表中找到对应学生修改其camp_group_id
				$student_id = $form->chargeman;
				// dd($student_id);
				$camp_group_id = $form->model()->id;
				$small_camp_id = Kly_camp::where('id',$camp_group_id)->value('pid');
				$big_camp_id = Kly_camp::where('id',$small_camp_id)->value('pid');
				Kly_student::where('student_id',$student_id)->update(['camp_group_id'=>$camp_group_id,'is_chargeman'=>1]);
            });
            //去掉添加/编辑表单的重置按钮
            $form->disableReset();
            $form->tools(function (Form\Tools $tools) {
                // 去掉`列表`按钮
                $tools->disableList();
                // 去掉`删除`按钮
                $tools->disableDelete();
                // 去掉`查看`按钮
                $tools->disableView();
            });
        });
    }
}